package com.hst.capacity.application.biz.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hst.capacity.application.biz.IntercityDispatchBiz;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.order.intercity.IntercityDriverTaskEntity;
import com.hst.capacity.domain.model.entity.order.intercity.IntercityOrderEntity;
import com.hst.capacity.domain.model.entity.order.intercity.IntercityOrderTaskEntity;
import com.hst.capacity.domain.model.entity.setting.line.CityLineEntity;
import com.hst.capacity.domain.model.entity.setting.line.IntercityLineEntity;
import com.hst.capacity.domain.model.request.intercity.dispatch.IcAddTaskParam;
import com.hst.capacity.domain.model.request.intercity.dispatch.IcDispatchDriverSearchParam;
import com.hst.capacity.domain.model.response.PagingResultVO;
import com.hst.capacity.domain.model.response.intercity.dispatch.IcCityLineCountDetail;
import com.hst.capacity.domain.model.response.intercity.dispatch.IcDispatchDriverDetailVO;
import com.hst.capacity.domain.model.response.intercity.dispatch.IcDispatchDriverSearchVO;
import com.hst.capacity.infra.convertor.IntercityConvertor;
import com.hst.capacity.infra.persistence.jpa.order.intercity.IcOrderRepository;
import com.hst.capacity.infra.persistence.jpa.order.intercity.IntercityDriverTaskRepository;
import com.hst.capacity.infra.persistence.jpa.order.intercity.IntercityOrderTaskRepository;
import com.hst.capacity.infra.persistence.jpa.setting.line.CityLineRepository;
import com.hst.capacity.infra.persistence.jpa.setting.line.IntercityLineRepository;
import com.hst.capacity.infra.persistence.mybatis.IntercityDispatchMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class IntercityDispatchBizImpl implements IntercityDispatchBiz {
    @Autowired
    private CityLineRepository cityLineRepository;
    @Autowired
    private IntercityLineRepository intercityLineRepository;
    @Autowired
    private IcOrderRepository icOrderRepository;
    @Autowired
    private IntercityDriverTaskRepository driverTaskRepository;
    @Autowired
    private IntercityOrderTaskRepository orderTaskRepository;
    @Autowired
    private IntercityDispatchMapper icDispatchMapper;


    @Override
    public List<IcCityLineCountDetail.IcCityLineCount> cityLineCount(String idFranchisee) {
        List<IcCityLineCountDetail.IcCityLineCount> converts = IntercityConvertor.INSTANCE.convert(cityLineRepository.findByIdFranchisee(idFranchisee));
        List<IntercityLineEntity> icLines = intercityLineRepository.findByIdFranchiseeAndIdCityLineIsNotNull(idFranchisee);
        List<IntercityOrderEntity> icOrders = icOrderRepository.findByIdFranchiseeAndStatus(idFranchisee, Constants.OrderStatus.ORDER_STATUS_CREATED);
        HashMap<String,Integer> map = new HashMap<>();
        HashMap<String,List<String>> map2 = new HashMap<>();
        for (IntercityLineEntity idLine:icLines){
            map.put(idLine.getIdLine(),0);
            if (!map2.containsKey(idLine.getIdCityLine()))map2.put(idLine.getIdCityLine(), new ArrayList<>());
            map2.get(idLine.getIdCityLine()).add(idLine.getIdLine());
        }
        for (IntercityOrderEntity icOrder:icOrders){
            if (map.containsKey(icOrder.getIdLine()))map.put(icOrder.getIdLine(),Integer.sum(map.get(icOrder.getIdLine()),1));
        }
        for (IcCityLineCountDetail.IcCityLineCount convert:converts){
            if (map2.containsKey(convert.getIdCityLine())){
                List<String> idLines = map2.get(convert.getIdCityLine());
                if (idLines.size()==1)convert.setOrderNumber(map.get(idLines.get(0)));
                if (idLines.size()==2)convert.setOrderNumber(Integer.sum(map.get(idLines.get(0)), map.get(idLines.get(1))));
                if (idLines.size()>=3)
                    throw new BusinessException(5002,convert.getIdCityLine()+"线路超出往返两条规定，请检查");
            }
        }
        return converts;
    }

    @Override
    public IcCityLineCountDetail cityLineCountDetail(String idFranchisee, String idCityLine) {
        IcCityLineCountDetail re = new IcCityLineCountDetail(cityLineCount(idFranchisee));
        if (re.getIcCityLineCounts().size()==0)throw new BusinessException(5002,"该运营商未开通任何线路");
        //未传idCityLine时默认选择第一个
        if (idCityLine!=null)re.setIdCityLineChecked(idCityLine);
        else re.setIdCityLineChecked(re.getIcCityLineCounts().get(0).getIdCityLine());
        List<IntercityLineEntity> byIdCityLine = intercityLineRepository.findByIdCityLine(re.getIdCityLineChecked());
        if (byIdCityLine.size()>=1)re.getGoLine().setIdLine(byIdCityLine.get(0).getIdLine()).setIntercityLineAlias(byIdCityLine.get(0).getIntercityLineAlias());
        if (byIdCityLine.size()>=2)re.getBackLine().setIdLine(byIdCityLine.get(1).getIdLine()).setIntercityLineAlias(byIdCityLine.get(1).getIntercityLineAlias());
        if (byIdCityLine.size()>=3)
            throw new BusinessException(5002,re.getIdCityLineChecked()+"线路超出往返两条规定，请检查");
        if (re.getGoLine()!=null)re.getGoLine().setOrders(IntercityConvertor.INSTANCE.convertOrder(icOrderRepository.findByIdLineAndStatus(re.getGoLine().getIdLine(), Constants.OrderStatus.ORDER_STATUS_CREATED)));
        if (re.getBackLine()!=null)re.getBackLine().setOrders(IntercityConvertor.INSTANCE.convertOrder(icOrderRepository.findByIdLineAndStatus(re.getBackLine().getIdLine(), Constants.OrderStatus.ORDER_STATUS_CREATED)));
        return re;
    }

    @Override
    public PagingResultVO<IcDispatchDriverSearchVO> icDispatchDriverSearch(IcDispatchDriverSearchParam param) {
        return new PagingResultVO(icDispatchMapper.searchTotal(param),icDispatchMapper.search(param));
    }

    @Override
    public IcDispatchDriverDetailVO icDispatchDriverDetail(String idDriver) {


        return null;
    }

    @Override
    public String icAddTask(IcAddTaskParam param) {
        IntercityDriverTaskEntity driverTaskEntity;
        try {
            driverTaskEntity=driverTaskRepository.findByIdDriverAndStatusLessThan(param.getIdDriver(), 3);//查询司机任务
        }catch (Exception e){
            throw new BusinessException(5002,"司机存在多个可派单任务，请检查");
        }
        if (driverTaskEntity==null){//创建任务
            driverTaskEntity=newIntercityDriverTaskEntity(param);
            driverTaskEntity=driverTaskRepository.save(driverTaskEntity);
        }else {//任务存在
            IntercityOrderEntity order;
            try {
                order = icOrderRepository.findById(param.getIdOrder()).get();
            }catch (NoSuchElementException e){
                throw new BusinessException(5002,"订单不存在");
            }
            //可能有订单重复加入任务的情况
            //更新任务表
            driverTaskEntity.setPassengersNumber(driverTaskEntity.getPassengersNumber()+order.getPassengerNumber());
            driverTaskEntity.setPassengersIncarNumber(driverTaskEntity.getPassengersIncarNumber()+order.getPassengerNumber());
            if (driverTaskEntity.getSeating()<driverTaskEntity.getPassengersIncarNumber()) throw new BusinessException(4003,"乘车人数超过可载人数,派单失败");

        }
        //加入订单
        IntercityOrderTaskEntity orderTaskEntity = new IntercityOrderTaskEntity();
        orderTaskEntity.setIdTask(driverTaskEntity.getIdTask());
        orderTaskEntity.setIdOrder(param.getIdOrder());
        orderTaskRepository.save(orderTaskEntity);
        return driverTaskEntity.getIdTask();
    }

    private IntercityDriverTaskEntity newIntercityDriverTaskEntity(IcAddTaskParam param){
        IntercityOrderEntity order;
        try {
            order = icOrderRepository.findById(param.getIdOrder()).get();
        }catch (NoSuchElementException e){
            throw new BusinessException(5002,"订单不存在");
        }
        IntercityDriverTaskEntity intercityDriverTaskEntity = new IntercityDriverTaskEntity();
//        intercityDriverTaskEntity.setIdTask();
        intercityDriverTaskEntity.setIdDriver(param.getIdDriver());
        intercityDriverTaskEntity.setIdLine(param.getIdLine());
//        intercityDriverTaskEntity.setIdSchedule();
//        intercityDriverTaskEntity.setScheduleTime();
//        intercityDriverTaskEntity.setIdFranchisee();
        intercityDriverTaskEntity.setIdShareRoute("");
        intercityDriverTaskEntity.setSeating(param.getSeats()-1);
        intercityDriverTaskEntity.setPassengersNumber(order.getPassengerNumber());
        intercityDriverTaskEntity.setPassengersIncarNumber(order.getPassengerNumber());
        intercityDriverTaskEntity.setTransportedPassengersNumber(0);
//        intercityDriverTaskEntity.setTaskSumMoney();
//        intercityDriverTaskEntity.setTaskAdditionalMoney();
//        intercityDriverTaskEntity.setTaskCouponMoney();
//        intercityDriverTaskEntity.setServiceType();
//        intercityDriverTaskEntity.setTaskType();
        intercityDriverTaskEntity.setStatus(1);
        intercityDriverTaskEntity.setDriverSubsidy(0f);
        intercityDriverTaskEntity.setDriverNoLoadSubsidy(0f);
//        intercityDriverTaskEntity.setMemo();
//        intercityDriverTaskEntity.setCreateBy();
//        intercityDriverTaskEntity.setCreateTime();
//        intercityDriverTaskEntity.setUpdateBy();
//        intercityDriverTaskEntity.setUpdateTime();
        return intercityDriverTaskEntity;
    }
}
